﻿"use strict";

// 初始化
function init()
{
    if ( ON_DEVICE )
    {
        // Wait for Cordova to load
        document.addEventListener("deviceready", onDeviceReady, false);
    }
    
    // 儲存全黑畫面
    storeNowDrawing();

    cleanPenHistory();
}

function showAlert( alertMessage )
{
    if ( ON_DEVICE )
    {
        navigator.notification.showAlert( "Message", null, "Title", alertMessage );
    }
    else
    {
        alert( alertMessage );
    }
}

// 印出除錯訊息
function printDebug( message )
{
    debugMessage.innerHTML += message;
}

// 印出最後一個除錯訊息
function printFinalDebug( message )
{
    debugMessage.innerHTML = message;
}

// 印出錯誤訊息
function printError( message )
{
    errorMessage.innerHTML += "發生錯誤: " + message + "<br";
}

// 允許畫筆運作
function unlockPen()
{
    gDrawLock = false;
}

// 禁止畫筆運作
function lockPen()
{
    gDrawLock = true;
}

// 檢查是否允許畫筆畫圖
function penIsLock()
{
    return gDrawLock;
}

// 清空畫筆歷史
function cleanPenHistory()
{
    gPenHistory = getGlobalValueHistory();

    for ( var i = 0; i < gPenMotionCount; i ++ )
    {
        clearTimeout( gPlayTimers[i] );
    }
}

function playPenHistoryAnimation( penOrder )
{
    return function()
    {
        //printDebug( "<br> Animation: " + penOrder );
        playPenHistory( penOrder );
    }
}

function playPenHistory( penOrder )
{
    
    if ( penOrder == 0 )
    {
        saveGlobal(); // 保存當下設置
        lockPen(); // 禁止畫筆運作
        cleanCanvas(); // 畫面清空   

        printDebug( gPenHistory ); // 印出歷史, for debug .
    }  

    var penTouchs = gPenHistory.split( TOUCH_GAP );
    gPenTouchCount = penTouchs.length - 1; // 此次下筆次數

    var penMotions = penTouchs[penOrder].split( MOTION_GAP );

    for ( var j = 0; j < penMotions.length - 1; j ++ )
    {
        //printDebug( "<br>第" + j + "步: " + penMotions[j] );
        setPlayTimer( penMotions[j].split( TOKEN_GAP ),  j + 1 );
    }

    //var debugString = gPenHistory; 

    //printDebug( "<br>->" + penOrder + " / " + gPenTouchCount + " : " + penMotions.length + "<br>" );

    if ( penOrder == gPenTouchCount)
    {
        unlockPen();
        restoreGlobal(); // 恢復設置
    }
    else
    {
        //printDebug( "" + penOrder + 1 + "," + penMotions.length );
        setTimeout( playPenHistoryAnimation( penOrder + 1 ), gPlaySpeed * penMotions.length + 1 );
    }
}

// 播放畫筆歷史
function playPenHistory2()
{
    lockPen(); // 禁止畫筆運作
    cleanCanvas(); // 畫面清空

    var penTouchs = gPenHistory.split( TOUCH_GAP );

    var debugString = gPenHistory;
    
    gPenTouchCount = penTouchs.length - 1; // 此次下筆次數
    
    for ( var i = 0; i < gPenTouchCount; i ++ )
    {
        debugString += "<br><br>" + "第" + i + "次下筆:";

        var penMotions = penTouchs[i].split( MOTION_GAP );
    
        //debugString += penMotions[i];

        for ( var j = 0; j < penMotions.length; j ++ )
        {
            debugString += "<br>第" + j + "步: " + penMotions[j];
            setPlayTimer( penMotions[j].split( TOKEN_GAP ), gPenMotionCount + j + 1 );
        }
        gPenMotionCount += penMotions.length; // 此次畫筆操作次數

        debugString += "<br>分解動作:" + penMotions.length;
        
    }

    debugString += "<br>共下筆: " + gPenTouchCount;

    //printDebug( debugString );
    printDebug( "pen:" + gPenTouchCount + ",timer:" + gPenMotionCount );
    
    // 畫筆解鎖，播放完畢才可繼續畫
    setTimeout( unlockPen(), gPlaySpeed * penMotions.length + 1 );
}

// (x,y) -> (x+offsetX, y+offsetY)
function shiftMotion( motion, offsetX, offsetY )
{
    var newMotion;

    var motionTokens = motion.split( TOKEN_GAP );
    
    var penStyle = motionTokens[0];

    if ( penStyle == TYPE_PEN_LINE )
    {
        newMotion = drawLine( parseInt( motionTokens[1] ) + offsetX, parseInt( motionTokens[2] ) + offsetY, parseInt( motionTokens[3] ) + offsetX, parseInt( motionTokens[4] ) + offsetY );
    }
    else if ( penStyle == TYPE_PEN_RECTANGLE )
    {
        newMotion = drawRectangle( parseInt( motionTokens[1] ) + offsetX, parseInt( motionTokens[2] ) + offsetY, parseInt( motionTokens[3] ) * ratio, parseInt( motionTokens[4] ) * ratio, motionTokens[5] );
    }
    else if ( penStyle == TYPE_PEN_CIRCLE )
    {
        newMotion = drawCircle( parseInt( motionTokens[1] ) + offsetX, parseInt( motionTokens[2] ) + offsetY );
    }
    else if ( penStyle == TYPE_PEN_DOT )
    {
        newMotion = drawDot( parseInt( motionTokens[1] ) + offsetX, parseInt( motionTokens[2] ) + offsetY );
    }
    else if ( penStyle == TYPE_TEXT )
    {
        newMotion = drawText( motionTokens[1], parseInt( motionTokens[2] ) + offsetX, parseInt( motionTokens[3] ) + offsetY, parseInt( motionTokens[4] ) * ratio, motionTokens[5] );
    }
    else if ( penStyle == TYPE_GLOBAL_VALUE )
    {
        newMotion = setGlobal( motionTokens[1], motionTokens[2], parseInt( motionTokens[3] ), parseInt( motionTokens[4] ) );
    }
    else
    {
        newMotion = motion;
    }

    return newMotion;
}

function resizeMotion( motion, ratio )
{
    var newMotion;

    var motionTokens = motion.split( TOKEN_GAP );
    
    var penStyle = motionTokens[0];

    if ( penStyle == TYPE_PEN_LINE )
    {
        newMotion = drawLine( parseInt( motionTokens[1] ) * ratio, parseInt( motionTokens[2] ) * ratio, parseInt( motionTokens[3] ) * ratio, parseInt( motionTokens[4] ) * ratio );
    }
    else if ( penStyle == TYPE_PEN_RECTANGLE )
    {
        newMotion = drawRectangle( parseInt( motionTokens[1] ) * ratio, parseInt( motionTokens[2] ) * ratio, parseInt( motionTokens[3] ) * ratio, parseInt( motionTokens[4] ) * ratio, motionTokens[5] );
    }
    else if ( penStyle == TYPE_PEN_CIRCLE )
    {
        newMotion = drawCircle( parseInt( motionTokens[1] ) * ratio, parseInt( motionTokens[2] ) * ratio );
    }
    else if ( penStyle == TYPE_PEN_DOT )
    {
        newMotion = drawDot( parseInt( motionTokens[1] ) * ratio, parseInt( motionTokens[2] ) * ratio );
    }
    else if ( penStyle == TYPE_TEXT )
    {
        newMotion = drawText( motionTokens[1], parseInt( motionTokens[2] ) * ratio, parseInt( motionTokens[3] ) * ratio, parseInt( motionTokens[4] ) * ratio, motionTokens[5] );
    }
    else if ( penStyle == TYPE_GLOBAL_VALUE )
    {
        newMotion = setGlobal( motionTokens[1], motionTokens[2], parseInt( motionTokens[3] ) * ratio, parseInt( motionTokens[4] ) );// / ratio );
    }
    else
    {
        newMotion = motion;
    }

    return newMotion;
}

// 改變 motion 的速度
function respeedMotion( motion, ratio )
{
    var newMotion;

    var motionTokens = motion.split( TOKEN_GAP );
    
    var penStyle = motionTokens[0];

    if ( penStyle == TYPE_GLOBAL_VALUE )
    {
        newMotion = setGlobal( motionTokens[1], motionTokens[2], parseInt( motionTokens[3] ), parseInt( motionTokens[4] ) * ratio );
    }
    else
    {
        newMotion = motion;
    }

    return newMotion;
}

// 將畫筆過往歷史改變整體尺寸
function respeedPenHistory( penHistory, ratio )
{
    saveGlobal();

    var newPenHistory = "";

    var motions = penHistory.split( MOTION_GAP );

    for ( var i = 0; i < motions.length; i ++ )
    {
        newPenHistory += respeedMotion( motions[i], ratio ) + MOTION_GAP;
    }

    restoreGlobal();

    return newPenHistory;// + getGlobalMotion() + MOTION_GAP;
}

// 將畫筆過往歷史改變整體尺寸
function shiftPenHistory( penHistory, offsetX, offsetY )
{
    saveGlobal();

    var newPenHistory = "";

    var motions = penHistory.split( MOTION_GAP );

    for ( var i = 0; i < motions.length; i ++ )
    {
        newPenHistory += shiftMotion( motions[i], offsetX, offsetY );// + MOTION_GAP;
    }

    restoreGlobal();

    return newPenHistory;// + getGlobalMotion() + MOTION_GAP;
}

// 將畫筆過往歷史改變整體尺寸
function resizePenHistory( penHistory, ratio )
{
    saveGlobal();

    var newPenHistory = "";

    var motions = penHistory.split( MOTION_GAP );

    for ( var i = 0; i < motions.length; i ++ )
    {
        newPenHistory += resizeMotion( motions[i], ratio );// + MOTION_GAP;
    }

    restoreGlobal();

    return newPenHistory;
}

function resetPenHistory( penHistory, x, y, width, height )
{
    var posData = getExtremePosData( penHistory );

    printDebug( "[X:" + posData.minX + "," + posData.maxX + "]" );
    printDebug( "[Y:" + posData.minY + "," + posData.maxY + "]" );

    var originalWidth = posData.maxX - posData.minX;
    var originalHeight = posData.maxY - posData.minY;
    var widthRatio = width / originalWidth;
    var heightRatio = height / originalHeight;
    var ratio;

    printDebug( originalWidth + "," + originalHeight );

    if ( widthRatio * originalHeight < height )
    {
        ratio = widthRatio;
    }
    else
    {
        ratio = heightRatio;
    }

    printDebug( "[" + gCanvas.width + "," + gCanvas.height + "][" + ratio + "][NEW SIZE:" + originalWidth * ratio + "," + originalHeight * ratio + "]" );

    penHistory = resizePenHistory( penHistory, ratio );
    posData = getExtremePosData( penHistory );

    var offsetX = x - ( posData.minX + posData.maxX ) / 2;
    var offsetY = y - ( posData.minY + posData.maxY ) / 2;

    printDebug( "[OFFSET:" + offsetX + "-" + offsetY + "]" );
    printDebug( "[X:" + ( posData.minX + offsetX ) + "," + ( posData.maxX + offsetX ) + "]" );
    printDebug( "[Y:" + ( posData.minY + offsetY ) + "," + ( posData.maxY + offsetY ) + "]" );

    return shiftPenHistory( penHistory, offsetX, offsetY );
}



// 設置畫筆播放器
function setPlayTimer( motionTokens, order )
{
    var speed = gPlaySpeed;
    
    var penStyle = motionTokens[0];

    if ( penStyle == TYPE_PEN_LINE )
    {
        setTimeout( drawLineAnimation( parseInt( motionTokens[1] ), parseInt( motionTokens[2] ), parseInt( motionTokens[3] ), parseInt( motionTokens[4] ) ), speed * order );
    }
    else if ( penStyle == TYPE_PEN_RECTANGLE )
    {
        setTimeout( drawRectangleAnimation( parseInt( motionTokens[1] ), parseInt( motionTokens[2] ), parseInt( motionTokens[3] ), parseInt( motionTokens[4] ), motionTokens[5] ), speed * order );
    }
    else if ( penStyle == TYPE_PEN_CIRCLE )
    {
        setTimeout( drawCircleAnimation( parseInt( motionTokens[1] ), parseInt( motionTokens[2] ) ), speed * order );
    }
    else if ( penStyle == TYPE_PEN_DOT )
    {
        setTimeout( drawDotAnimation( parseInt( motionTokens[1] ), parseInt( motionTokens[2] ) ), speed * order );
    }
    else if ( penStyle == TYPE_TEXT )
    {
        // text, x, y, textWidth, fontColor
        setTimeout( drawTextAnimation( motionTokens[1], parseInt( motionTokens[2] ), parseInt( motionTokens[3] ), parseInt( motionTokens[4] ), motionTokens[5] ), speed * order );
    }
    else if ( penStyle == TYPE_GLOBAL_VALUE )
    {
        //printDebug( "c" );
        setTimeout( setGlobalAnimation( motionTokens[1], motionTokens[2], parseInt( motionTokens[3] ), parseInt( motionTokens[4] ) ), speed * ( order ) );

        // 第一個動作是設置全域變數，代表需先設定時間
        if ( order == 1 )
        {
            gPlaySpeed = parseInt( motionTokens[4] );
        }
    }
}




// 在指定時間設定全域變數
function setGlobalAnimation( backColor, penColor, penWidth, playSpeed )
{
    return function()
    {
        setGlobal( backColor, penColor, penWidth, playSpeed );
    }
}

// 設定全域變數
function setGlobal( backColor, penColor, penWidth, playSpeed )
{
    gBackColor = backColor;
    gPenColor = penColor;
    gPenWidth = penWidth;
    gPlaySpeed = playSpeed;

    return "" + TYPE_GLOBAL_VALUE + TOKEN_GAP + getColorHistory( backColor ) + TOKEN_GAP + getColorHistory( penColor ) + TOKEN_GAP + penWidth + TOKEN_GAP + playSpeed + MOTION_GAP;
}

// 取得當前global變數的motion
function getGlobalMotion()
{
    return setGlobal( gBackColor, gPenColor, gPenWidth, gPlaySpeed );
}

function setPenColor( penColor )
{
    gPenColor = penColor;
}

function setPenWidth( penWidth )
{
    gPenWidth = penWidth;
}

// 將目前全域變數都存起來
function saveGlobal()
{
    gTempBackColor = gBackColor;
    gTempPenColor = gPenColor;
    gTempPenWidth = gPenWidth;
    gTempPlaySpeed = gPlaySpeed;
}

// 將之前存的變數吐出來
function restoreGlobal()
{
    gBackColor = gTempBackColor;
    gPenColor = gTempPenColor;
    gPenWidth = gTempPenWidth;
    gPlaySpeed = gTempPlaySpeed;    
}

// 調整畫筆寬度
function addPenWidth()
{
    gPenHistory += setGlobal( gBackColor, gPenColor, gPenWidth + 10, gPlaySpeed );

    printFinalDebug( "[" + gPenWidth + "]" );
}

// 調整畫筆寬度
function cutPenWidth()
{
    gPenHistory += setGlobal( gBackColor, gPenColor, gPenWidth - 9, gPlaySpeed );

    printFinalDebug( "[" + gPenWidth + "]" );
}

// 設置目前畫筆樣式
function setPenStyle( penStyle )
{
    gPenStyle = penStyle;
}


// 存入最新畫面
function storeNowDrawing()
{
    gDrawingIndex++;
    
    if ( gDrawingIndex == DRAWING_MAX_COUNT )
    {
        gDrawingIndex = 0;
    }
    
    gDrawingHistory[gDrawingIndex] = gCanvas.toDataURL();
}

// 取出最後一張儲存的畫面
function getNowDrawing()
{
    if ( gDrawingHistory[gDrawingIndex] == null )
    {
        showAlert( "沒有儲存畫面" );

        return null;
    }

    return gDrawingHistory[gDrawingIndex];
}

// 取出前一張畫面
function getPrevDrawing()
{
    var tempIndex = gDrawingIndex - 1;
    
    if ( tempIndex < 0 )
    {
        tempIndex = DRAWING_MAX_COUNT - 1;
    }

    if ( gDrawingHistory[tempIndex] != null )
    {
        gDrawingIndex = tempIndex;
        return gDrawingHistory[gDrawingIndex];
    }
    
    showAlert( "沒存貨了" );
    
    return null;
}

// 取出下一張畫面
function getNextDrawing()
{
    var tempIndex = gDrawingIndex + 1;
    
    if ( tempIndex == DRAWING_MAX_COUNT )
    {
        tempIndex = 0;
    }
    
    if ( gDrawingHistory[tempIndex] != null )
    {
        gDrawingIndex = tempIndex;
        return gDrawingHistory[gDrawingIndex];
    }
    
    showAlert( "到上限了" );
    
    return null;
}

/*
// 回到下一步
function redo()
{
    try 
    {
        var imageObj = new Image();

        imageObj.onload = function() {
            gContext.drawImage( imageObj, 0, 0 );
        };
        imageObj.src = getNextDrawing();
    }
    catch ( err )
    {
        printError( err.stack );
    }
}

// 回到上一步
function undo()
{
    try 
    {
        cleanCanvas(); // 先清空畫面
        //getPrevDrawing(); // 把最新的畫面取出
        
        var imageObj = new Image();

        imageObj.onload = function() {
            gContext.drawImage( imageObj, 0, 0 );
        };
        imageObj.src = getPrevDrawing();
    }
    catch ( err )
    {
        printError( err.stack );
    }
}
*/




// about DOM

// 取得輸入框的內容
function getInputValue( inputElement )
{

    var text = inputElement.value;
    showAlert( text );

    return text;
}

// 刪除輸入框
function removeInputField()
{
    var divElement = document.getElementById( "inputDiv" );
    //var inputElement = document.getElementById( "inputText" );

    if ( divElement != null )
    {
        document.body.removeChild( divElement );
    }
}

// 產生輸入框
function createInputField()
{
    try 
    {
        var txtNode = document.createTextNode("Hello. This is a new node."); 
        
        var divElement = document.createElement( "inputDiv" );//document.getElementById( "inputDiv" );
        divElement.id = "inputDiv";
        divElement.size = "100%";
        divElement.style.position = "absolute";
        divElement.style.left = "20%";
        divElement.style.top = "30%";
        
        document.body.appendChild( divElement );
        
        var inputElement = document.createElement( "input" );
        inputElement.id = "inputText";
        inputElement.setAttribute( "type", "text" );
        inputElement.onkeydown = function( event )
        {
            if (event.keyCode == 13) 
            {
                gInputText = getInputValue( inputElement );
                gDrawText = encodeText( gInputText );
            }
        }

        divElement.appendChild( inputElement );
        
        
        
        /*
        var newElement = document.createElement( "div" );
        newElement.id = "inputDiv";
        //newElement.className = "inputClass";
        //newElement.setAttribute('name ','newDivName');
        newElement.style.width  = '280px';
        newElement.style.height = '200px';
        newElement.style.left = "269px"; 
        newElement.style.top = "175px";
        newElement.style.position = "absolute";
        */
        //newElement.appendChild(newText);
        //document.body.appendChild(newElement);
    }
    catch ( err )
    {
        printError( err.stack );
    }
}

// get a random number ( 0 ~ range ) .
function getRandom( range )
{
    return parseInt( Math.random() * range );
}

// 取得隨機顏色
function getRandomColor()
{
    var r = getRandom( 220 ) + 20;
    var g = getRandom( 220 ) + 20;
    var b = getRandom( 220 ) + 20;

    return "#" + r.toString( 16 ) + g.toString( 16 ) + b.toString( 16 );
}

// 取得畫筆紀錄中的最左上和最右下的坐標
function getExtremePosData( penHistory )
{
    var motions = penHistory.split( MOTION_GAP );
    
    var minX = 10000;
    var maxX = 0;
    var minY = 10000;
    var maxY = 0;

    // 找出左上角和右下角
    for ( var i = 0; i < motions.length; i ++ )
    {
        var tokens = motions[i].split( TOKEN_GAP );
        var type = parseInt( tokens[0] );

        // 只找畫筆的部份
        if ( type == TYPE_PEN_LINE )
        {
            var x = parseInt( tokens[1] );
            var y = parseInt( tokens[2] );
            var destX = parseInt( tokens[3] );
            var destY = parseInt( tokens[4] );

            //if ( x != destX && y != destY )
            {
                minX = x < minX ? x : minX;
                maxX = x > maxX ? x : maxX;

                minY = y < minY ? y : minY;
                maxY = y > maxY ? y : maxY;
            }
        }
    }

    return new ExtremePosData( minX, minY, maxX, maxY );
}

// 建立範圍在penHistory內的按鈕，上面顯示buttonText .
function createButton( penHistory, buttonText )
{
    var posData = getExtremePosData( penHistory );

    var buttonX = ( posData.minX + posData.maxX ) / 2;
    var buttonY = ( posData.minY + posData.maxY ) / 2;
    var buttonWidth = posData.maxX - posData.minX;
    var buttonTextColor = gPenColor;

    penHistory += drawText( buttonText, buttonX, buttonY, buttonWidth, buttonTextColor );

    addButton( BUTTON_COLOR, posData.minX, posData.minY, posData.maxX - posData.minX, posData.maxY - posData.minY );

    return penHistory;
}

// 向系統註冊此案扭，只要點擊的位置(x,y)符合: 
// minX < x < maxX && minY < y < minY , 即判定點擊此按鈕 
function addButton( type, minX, minY, width, height )
{
    gButtons[gNowButtonCount] = new ButtonData( gNowButtonCount, gNowPage, type, minX, minY, width, height );

    gNowButtonCount++;
}

// return true : 刪除編號no 的按鈕成功
//        false: 找不到編號no的按鈕
function removeButton( no )
{
    for ( var i = 0; i < BUTTON_MAX_COUNT; i++ )
    {
        if ( gButtons[i] != null )
        {
            if ( gButtons[i].no == no )
            {
                gButtons[i] = null;

                gNowButtonCount--;

                return true;
            }
        }
    }

    return false;
}

// 清除所有按鈕對系統的註冊
function cleanButtons()
{
    for ( var i = 0; i < BUTTON_MAX_COUNT; i++ )
    {
        gButtons[i] = null;
    }

    gNowButtonCount = 0;
}

// return n : (x,y)按到的按鈕型別
// return NOT_FOUND : 沒按到按鈕
function getButtonNo( x, y )
{
    for ( var i = 0; i < BUTTON_MAX_COUNT; i ++ )
    {
        // 在button區域範圍內
        if ( gButtons[i] != null && 
             gButtons[i].x <= x && gButtons[i].y <= y &&
             gButtons[i].x + gButtons[i].width >= x && gButtons[i].y + gButtons[i].height >= y )
        {
            return gButtons[i].no;
        }
    }

    return NOT_FOUND;
}

function getButtonType( buttonNo )
{
    return gButtons[buttonNo].type;
}

// 這個按鈕是否點擊後需要跳轉到某個頁面
function enterPageByButton( buttonNo )
{
    var buttonType = getButtonType( buttonNo );

    if ( buttonType == BUTTON_COLOR )
    {
        showColorBox();
    }
    else if ( buttonType == BUTTON_PEN )
    {

    }
}

function getColorHistory( color )
{
    return color;
}

// 取得單次設置歷史字串
function getGlobalValueHistory()
{
    return "" + TYPE_GLOBAL_VALUE + TOKEN_GAP + getColorHistory( gBackColor ) + TOKEN_GAP + getColorHistory( gPenColor ) + TOKEN_GAP + gPenWidth + TOKEN_GAP + gPlaySpeed + MOTION_GAP; 
}


// 回傳是點擊到哪個物件
function getTouchType( x, y )
{
    var buttonNo = getButtonNo( x, y );
    
    return buttonNo;
}


function createMessage()
{

}

/*
// ongoing function :
1. createInputField()
2. createButton()
3. createMessage()
4. showPenBox()
5. showColorBox()
6. showFunctionBox()

// effect
1. shake()
2. reel()

button design pattern :
1. always in system.
2. only register the buttons shows on 

*/

//type, width, color, timeSlot, RESERVE_VALUE

function showDemoButton()
{
    saveGlobal();

    var demoHistory = "";

    //gPenHistory = createButton( demoPenHistory, encodeText( "Hello World" ) );

    //gPenHistory = resizePenHistory( getNumberHistory( 2 ), 0.5 );
    //gPenHistory = shiftPenHistory( gPenHistory, 100, 100 );
    //gPenHistory = getNumberHistory( 2 );

    //gPenHistory = resetPenHistory( getNumberHistory( 3 ), 200, 200, 100, 100 ); 
    //gPenHistory += resetPenHistory( getNumberHistory( 4 ), 400, 200, 150, 100 ); 
    //demoHistory += resetPenHistory( getNumberHistory( 3 ), 100, 100, 200, 500 ); 

    drawDisable();
   
    var x = 200;
    var y = 200;
    var width = 100;
    var height = 100;
    var offset = height / 10;

    for ( var i = 0; i < 2; i ++ )
    {
        demoHistory += getBoxHistory( x, y + ( height + offset ) * i, width, height ); 
    }
    
    //demoHistory += drawRectangle( x - width / 2, y - height / 2, width, height, gPenColor );

    //printDebug( demoHistory );

    restoreGlobal();

    drawEnable();

    gPenHistory = demoHistory + getGlobalMotion();

    //printDebug( gPenHistory );

    //gPenHistory = getLineHistory( 3 );
    //gPenHistory = resetPenHistory( getLineHistory( 3 ), 100,100,100,100 );

    playPenHistory( 0 );
}

// 
function getBoxHistory( x, y, width, height )
{
    var speed = 10;
    var history = getGlobalMotion();
    
    history += resetPenHistory( getLineHistory( 1, 10, gPenColor, speed ), x - width / 2, y, height, height ); 
    history += resetPenHistory( getLineHistory( 2, 10, gPenColor, speed ), x, y + height / 2, width, width ); 
    history += resetPenHistory( getLineHistory( 1, 10, gPenColor, speed ), x + width / 2, y, height, height );
    history += resetPenHistory( getLineHistory( 2, 10, gPenColor, speed ), x, y - height / 2, width, width );

    history += resetPenHistory( getFixHistory( "green", speed / 2 ), x, y, width * 0.8, height * 0.8 );

    //history += drawRectangle( x - width / 2, y - height / 2, width, height, gPenColor );
    
    
    return history;
}

// 允許繪圖
function drawEnable()
{
    gDrawEnable = true;
}

// 禁止繪圖
function drawDisable()
{
    gDrawEnable = false;
}

// 編碼後的字串（將那些gap字元以特定字元取代）
function encodeText( text )
{
    return text.replace( TOUCH_GAP, ENCODE_TOUCH_GAP ).replace( MOTION_GAP, ENCODE_MOTION_GAP ).replace( TOKEN_GAP, ENCODE_TOKEN_GAP );
}

// 將字串解碼
function decodeText( text )
{
    return text.replace( ENCODE_TOUCH_GAP, TOUCH_GAP ).replace( ENCODE_MOTION_GAP, MOTION_GAP ).replace( ENCODE_TOKEN_GAP, TOKEN_GAP );
}

// 印出坐標, for debug
function showDetailPos()
{
    for ( var i = 0; i < gCanvas.width; i += 100 )
    {
        for ( var j = 0; j < gCanvas.height; j += 100 )
        {
            draw( i, j );
        }
    }
}



// 1. 研究照比例縮小
// 2. 將每個數字存檔

